import 'dart:async';

import 'package:flutter/material.dart';
import 'package:hktk_app/dao/home_dao.dart';
import 'package:hktk_app/dao/subject_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/home/column_position_enum.dart';
import 'package:hktk_app/ienum/home/column_type_enum.dart';
import 'package:hktk_app/ienum/my/up_load_enum.dart';
import 'package:hktk_app/model/home/column_model.dart';
import 'package:hktk_app/model/page/resource_page_model.dart';
import 'package:hktk_app/model/subject/paper_model.dart';
import 'package:hktk_app/util/dao_util.dart';
import 'package:hktk_app/util/event_bus_util.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/subject/purchase_tips_widget.dart';
import 'package:hktk_app/widget/subject/true_question_widget.dart';

/// 历年真题详情页面展示
class QuestionDetailPage extends StatefulWidget {
  /// 对应tabId（科目id）
  final int subId;

  /// 栏目名称，做对应使用
  final String columnName;

  const QuestionDetailPage({
    super.key,
    required this.subId,
    required this.columnName,
  });

  @override
  State<QuestionDetailPage> createState() => _QuestionDetailPageState();
}

class _QuestionDetailPageState extends State<QuestionDetailPage> {
  late BuildContext _context;

  /// 是否显示未购买
  late bool _showTips;

  /// 加载数据方法
  late Future<Map<String, dynamic>> _futureInit;

  /// 相关对应数据
  late List<PaperModel> _list;

  /// 列表滑动控制器
  late ScrollController _scrollController;

  /// 栏目id
  late String _columnId;

  /// 加载页面
  late int _page;

  /// 每一页加载的条数
  late int _size;

  /// 加载中，
  late bool _loading;

  /// 加载状态，0：什么都不显示，1：表示加载中，2：表示没有数据了
  late UploadEnum _loadType;

  /// 监听试卷详情页关闭方法
  late StreamSubscription<EventPaperDetailClose> _eventPaperClose;

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    _showTips = false;
    _columnId = "";
    _page = 1;
    _size = 10;
    _loading = false;
    _loadType = UploadEnum.loading;
    _list = [];
    _futureInit = _initData();

    // 监听是否滑动到底部，实现上拉加载功能
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _loadDataInit();
      }
    });

    // 监听试卷详情是否返回
    _eventPaperClose = eventBus.on<EventPaperDetailClose>().listen((event) {
       if (event.columnId == _columnId) {
        setState(() {
          _list[event.index].recordId = event.recordId;
        });
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
    _eventPaperClose.cancel();
  }

  @override
  Widget build(BuildContext context) {
    _context = context;
    return FutureBuilder<Map<String, dynamic>>(
      future: _futureInit,
      builder: (
          BuildContext context,
          AsyncSnapshot<Map<String, dynamic>> snapshot,
          ) {
        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> map = snapshot.data!;
          if (!map["suc"]) {
            // 加载数据失败
            if (map["msg"] != null) {
              WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
                ToastUtil.show(context: _context, msg: map["msg"]);
              });
            }
          }
          return _content();
        } else {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }

  /// 加载数据方法
  _loadDataInit() {
    if (_loadType == UploadEnum.def) {
      setState(() {
        _loadType = UploadEnum.noData;
      });
    } else if (_loadType == UploadEnum.loading) {
      if (!_loading) {
        _loading = true;
        _page++;
        _loadData().then((Map<String, dynamic> map) {
          // 加载完成
          if (!map["suc"]) {
            ToastUtil.show(context: _context, msg: map["msg"]);
          }
          setState(() {
            _loading = false;
          });
        });
      }
    }
  }

  /// 加载更多数据
  Future<Map<String, dynamic>> _loadData() async {
    Map<String, dynamic> map = {};
    try {
      // 根据栏目加载试卷
      ResourcePageModel<PaperModel> page = await SubjectDao.paperByColumnId(
        size: _size,
        current: _page,
        columnId: _columnId,
        countDetail: true,
      );
      List<PaperModel> list = page.records!;
      _list.addAll(list);
      // 判断是否显示加载
      if (_list.length == page.total) {
        _loadType = UploadEnum.noData;
      }
      // 判断是否显示未购买
      _showTips = false;
      for (PaperModel model in list) {
        if (model.free == false) {
          _showTips = true;
          break;
        }
      }
      map["suc"] = true;
    } catch (e) {
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 初始化数据方法
  Future<Map<String, dynamic>> _initData() async {
    Map<String, dynamic> map = {};
    try {
      // 加载数据
      // 根据科目加载对应栏目
      List<ColumnModel> list = await HomeDao.columnByCategory(
        categoryId: widget.subId,
        groupId: getGroupId(),
        columnEnum: ColumnPositionEnum.jgqy,
      );
      for (ColumnModel model in list) {
        if (model.type == ColumnTypeEnum.paperLibrary &&
            model.name == widget.columnName) {
          _columnId = model.id!;
          break;
        }
      }
      if (_columnId == "") {
        return {"suc": true};
      }
      // 根据栏目加载试卷
      ResourcePageModel<PaperModel> page = await SubjectDao.paperByColumnId(
        size: _size,
        current: _page,
        columnId: _columnId,
        countDetail: true,
      );
      _list = page.records!;
      // 判断是否显示加载
      if (_list.length < _size) {
        _loadType = UploadEnum.def;
      }
      // 判断是否显示未购买
      _showTips = false;
      for (PaperModel model in _list) {
        if (model.free == false) {
          _showTips = true;
          break;
        }
      }

      map["suc"] = true;
    } catch (e) {
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 内容显示方法
  Widget _content() {
    return Stack(
      children: [
        _contentItem(),
        if (_showTips)
          PurchaseTipsWidget(
            columnId: _columnId,
          ),
      ],
    );
  }

  /// 主要内容显示
  _contentItem() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 24),
      padding: EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: colorWhite1,
        borderRadius: BorderRadius.all(Radius.circular(20)),
      ),
      child: _listItem(),
    );
  }

  _listItem() {
    if (_list.isNotEmpty) {
      return MediaQuery.removePadding(
        removeTop: true,
        context: _context,
        child: ListView.separated(
          itemBuilder: _itemBuilder,
          separatorBuilder: _separatorBuilder,
          itemCount: _list.length + 1,
          controller: _scrollController,
        ),
      );
    } else {
      return showNoData(text: _columnId == "" ? "无相关数据" : null);
    }
  }

  /// listItem显示
  Widget? _itemBuilder(BuildContext context, int index) {
    if (index < _list.length) {
      PaperModel model = _list[index];
      return TrueQuestionWidget(
        paper: model,
        columnId: _columnId,
        index: index,
      );
    }
    return _loadItem();
  }

  /// item 之间的间隔显示
  Widget _separatorBuilder(BuildContext context, int index) {
    return hiSpace(height: 48);
  }

  /// 加载中组件
  Widget? _loadItem() {
    return Container(
      height: 82,
      margin: EdgeInsets.only(bottom: _showTips ? 96 : 0),
      child: _loadConItem(),
    );
  }

  /// 加载组件具体显示
  _loadConItem() {
    if (_loadType == UploadEnum.def) {
      return null;
    } else if (_loadType == UploadEnum.loading) {
      // 加载中
      return Center(
        child: SizedBox(
          width: 40,
          height: 40,
          child: CircularProgressIndicator(
            strokeWidth: 4,
          ),
        ),
      );
    } else if (_loadType == UploadEnum.noData) {
      return Container();
      // 没有数据，我是有底线的
      // return Center(
      //   child: Text(
      //     "我是有底线的！",
      //     style: FontUtil.fontBlue1(22),
      //   ),
      // );
    }
  }
}
